import Vue from 'vue'
import Vuex from 'vuex'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import api from 'api'
import race from './modules/race'
import employee from './modules/employee'
import sponsor from './modules/sponsor'
import history from './modules/history'
import organize from './modules/organize'
import authorize from './modules/authorize'
import brand from './modules/brand'
import order from './modules/order'
import message from './modules/message'
import service from './modules/service'
import train from './modules/train'
import tickets from './modules/tickets'
import merchants from './modules/merchants'
Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

// state
let state = {
  loading: false,
  layout_grid: true, // 是否栅格布局
  check_account: true, // 账号是否存在
  global: { // 公共数据
    user: {},
    list: [],
    api_prefix: 'http://org.htxk.dev/api/',
    authOrgId: ''
  },
  token: localStorage.getItem('htxk_token') || '',
  userId: localStorage.getItem('htxk_userId') || ''
}

// getters
const getters = {
  global: state => state.global,
  user: state => state.global.user,
  loading: state => state.loading,
  layout_grid: state => state.layout_grid,
  check_account: state => state.check_account,
  token: state => state.token,
  userId: state => state.userId
}

// actions
const actions = {
  check_account ({commit, state}, params) {
    api.checkAccount(params).then((res) => {
      commit('CHECK_ACCOUNT', {data: res})
    }).catch((ERR) => {
      return false
    })
  },
  reset_info ({commit, state}) {
    commit('RESET_INFO')
  }
}

// mutations
const mutations = {
  LOGIN (state, data) {
    state.global.user = data
  },
  SET_TOKEN (state, data) {
    localStorage.setItem('htxk_token', data.token)
    localStorage.setItem('htxk_userId', data.userId)
    state.userId = data.userId
    state.token = data.token
  },
  LOADING (state, value) {
    value === true && (window.laser.fetchCount = 0)
    state.loading = value
    if (value) {
      NProgress.start()
    } else {
      NProgress.done()
    }
  },
  LAYOUT_GRID (state, value) { // 设置左侧siderBar是否可见
    state.layout_grid = value
  },
  CHECK_ACCOUNT (state, {data}) {
    state.check_account = data.data
  },
  RESET_INFO (state) {
    localStorage.removeItem('htxk_token')
    localStorage.removeItem('htxk_userId')
  }
}

const store = new Vuex.Store({
  state,
  actions,
  getters,
  mutations,
  modules: {
    race,
    employee,
    sponsor,
    history,
    organize,
    authorize,
    brand,
    order,
    message,
    service,
    train,
    tickets,
    merchants
  },
  strict: false,
  debug: debug
})

export default store
